package com.groupbuying.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.groupbuying.customer.connector.CurrencyFeign;
import com.groupbuying.customer.connector.SysconfigFeign;
import com.groupbuying.customer.connector.WechatAliFeign;
import com.groupbuying.customer.constants.CommonConstants;
import com.groupbuying.customer.constants.CustomerUshopSearchConstants;
import com.groupbuying.customer.constants.CustomerWxinfoRelSearchConstants;
import com.groupbuying.customer.dao.CustomerUshopDao;
import com.groupbuying.customer.dao.CustomerWxinfoRelDao;
import com.groupbuying.customer.domain.CustomerDO;
import com.groupbuying.customer.domain.CustomerUshopDO;
import com.groupbuying.customer.domain.CustomerWxinfoRelDO;
import com.groupbuying.customer.domain.UserToken;
import com.groupbuying.customer.mq.CustomerMQConfig;
import com.groupbuying.customer.service.CustomerService;
import com.groupbuying.customer.service.CustomerUshopService;
import com.groupbuying.customer.service.CustomerWxinInfoService;
import com.groupbuying.customer.service.CustomerWxinfoRelService;
import com.groupbuying.customer.utils.JwtUtils;
import com.groupbuying.customer.utils.apiresult.ApiResult;
import com.groupbuying.customer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author gxy
 * @Description 会员微信账户信息相关业务
 * @Date 2019/5/14 10:10
 **/

@Service
public class CustomerWxinInfoServiceImpl implements CustomerWxinInfoService {
    private Logger log = LoggerFactory.getLogger(CustomerWxinInfoServiceImpl.class);

    @Autowired
    private CustomerWxinfoRelService customerWxinfoRelService;

    @Autowired
    private CustomerWxinfoRelDao customerWxinfoRelDao;

    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private CustomerUshopService customerUshopService;

    @Autowired
    private Producer producer;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerUshopDao customerUshopDao;
    @Autowired
    private WechatAliFeign wechatAliFeign;

    @Autowired
    private CurrencyFeign currencyFeign;
    /**
     * //通过customerId获取用户openId
     *
     * @Author Vincentxin
     * @Date 2019/10/24 11:04
     * @param customerId
     * @return java.lang.String
     **/
    @Override
    public String getOpenidByCustomerId(String customerId) {
        CustomerWxinfoRelDO customerWxinfoRelDO = customerWxinfoRelService.get(customerId);
        if (customerWxinfoRelDO != null) {
            return customerWxinfoRelDO.getOpenId();
        }
        return null;
    }

    /**
     * 微信小程序用户手机号授权的注册登录
     *
     * @param decryptedData 加密手机号信息
     * @param iv            解密初始化偏移量
     * @param code          用户小程序登录的code
     * @return com.groupbuying.customer.utils.apiresult.ApiResult
     * @Author Vincentxin
     * @Date 2019-08-16 10:30
     **/

    @Override
    @Transactional
    public ApiResult getPhoneNumByDecryptedData(String decryptedData, String iv, String code) {
        Map<String,String> wxMobileMsg = wechatAliFeign.decryptData(decryptedData,iv,code,"youdianproductor");
        log.info("微信授权信息解密信息:{}", wxMobileMsg);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mqParams = new HashMap<>();
        if (wxMobileMsg == null || wxMobileMsg.size()<2) {
            return ApiResult.failure(ApiResultCode.AUTHORIZATIONFAILURE,"授权信息解密失败");
        }
        CustomerWxinfoRelDO customerWxinfoRelDO = customerWxinfoRelDao.getByOpenId(wxMobileMsg.get("openid"));
        log.info("获取微信关联customerWxinfoRelDO:{}", customerWxinfoRelDO);
        CustomerUshopDO customerUshopDO = new CustomerUshopDO();
        //获取到微信解析手机号
        //获取到微信解析openid
        String phone = wxMobileMsg.get("phoneNumber");
        String openid = wxMobileMsg.get("openid");
        log.info("获取微信手机号:{},openID:{}", phone, openid);
      //异步传输对象容器
        Map<String, Object> data = new HashMap<>();
        boolean isNewCur = false;

        if (customerWxinfoRelDO == null) {
            //创建子账号平台
            customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
            customerUshopDO.setGmtCreate(new Date());
            customerUshopDO.setGmtModified(new Date());
            customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
            customerUshopDO.setType(CommonConstants.MLS);
            customerUshopDO.setMobile(wxMobileMsg.get("phoneNumber"));
            customerUshopDO.setMainUuid("");
            customerUshopService.save(customerUshopDO);
            log.info("绑定优店信息为:{}", customerUshopDO);
            //创建微信与用户关系
            customerWxinfoRelDO = new CustomerWxinfoRelDO();
            customerWxinfoRelDO.setCustomerId(customerUshopDO.getCustomerId());
            customerWxinfoRelDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
            customerWxinfoRelDO.setGmtCreate(new Date());
            customerWxinfoRelDO.setGmtModified(new Date());
            customerWxinfoRelDO.setOpenId(wxMobileMsg.get("openid"));
            log.info("绑定微信用户信息为:{}", customerWxinfoRelDO);
            customerWxinfoRelService.save(customerWxinfoRelDO);

        } else {
            //关系表存在该用户id，证明用户已注册
            String customerId = customerWxinfoRelDO.getCustomerId();
            //通过customerId获取用户主表对应信息
            customerUshopDO = customerUshopDao.get(customerId);
            log.info("通过customerId获取的优店信息为:{}", customerUshopDO);
            //获取Ushop的手机号
            String mobile = customerUshopDO.getMobile();
            log.info("获取的优店手机号为:{}", mobile);
            if (StringUtils.isEmpty(mobile)) {
                log.error("已注册手机号为空");
                CustomerUshopDO customerUshopDO1 = customerUshopDao.getUshopByMobile(phone);
                log.info("通过微信手机号获取优店信息为:{}", customerUshopDO1);
                //这个账户有没有注册过
                if (customerUshopDO1 == null) {
                    customerUshopDO.setMobile(phone);
                    customerUshopDO.setGmtModified(new Date());
                    log.info("优店信息更新为:{}", customerUshopDO);
                    customerUshopDao.update(customerUshopDO);
                    //TODO 注册积分账户
                    Map searchMap = new HashMap();
                    searchMap.put(CustomerUshopSearchConstants.SEARCH_CUSTOMERID, customerUshopDO.getCustomerId());
                    Map res = currencyFeign.createCurrencyCustomer(searchMap);
                    if (res.size()>0){
                        isNewCur = true;
                    }
                } else {
                    //注册过
                    //主键不相等
                    customerWxinfoRelDO.setCustomerId(customerUshopDO1.getCustomerId());
                    customerWxinfoRelDO.setGmtModified(new Date());
                    try{
                        customerWxinfoRelDao.updateByOpenId(customerWxinfoRelDO);
                    }catch (DuplicateKeyException e){
                        customerWxinfoRelDao.remove(customerUshopDO1.getCustomerId());
                        customerWxinfoRelDao.updateByOpenId(customerWxinfoRelDO);
                    }
                    //这么写的目的是让用户切换，然后生成token与代码逻辑统一
                    customerUshopDO=customerUshopDO1;
                }
            }

        }

        List<CustomerDO> customers = customerService.getCustomerByMobile(phone);
        if (customers.size() == 0){
            //发送mq到老够样
            try {
                mqParams.put("userName", phone);
                mqParams.put("mobile", phone);
                mqParams.put("password", phone.substring(phone.length()-6));
                Message message = new Message(CustomerMQConfig.GY_TOPIC, CustomerMQConfig.MOBILE_REGISTERED, JSON.toJSONString(mqParams, SerializerFeature.DisableCircularReferenceDetect).getBytes());
                producer.send(message);
                log.info("mq发送成功");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("mq发送失败：{}",e.getMessage());
            }
        }

        try {
            UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            map.put("token", token);
            map.put("phoneNumber", wxMobileMsg.get("phoneNumber"));
            map.put("wxMobileMap", wxMobileMsg);
            map.put("giftCur", isNewCur==true? "10":"");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Token 生成失败");
            return ApiResult.failure("token获取失败");
        }
        return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, map);
    }

    /**
     * 发送的用户中心消费模块的工具方法。
     *
     * @param obj 消息传递对象
     */
    private void sendMsgToMQ(Object obj, String tag) throws Exception {
        //创建子账号平台
        Message orderMessage = new Message(CustomerMQConfig.TOPIC, tag,
                JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect).getBytes());
        producer.send(orderMessage);
    }



}
